# coding:utf-8
# 战斗单位

import math
import glog, glb
import DATA_enemy
from glb import BATTLE_SIDE_A, BATTLE_SIDE_B, BATTLE_FRAME_PER_SECOND


class BattleUnit:
	def __init__(self, is_player, side, x, y, type, atk, dfn, hp, spd, skill):
		# 属性
		self.is_player = is_player
		self.side = side
		self.x = x
		self.y = y
		self.type = type
		self.atk = atk
		self.dfn = dfn
		self.hp = hp
		self.mhp = hp
		self.spd = spd

		# 通过type查表
		self.skill = skill
		self.attack_speed_frames = 5 # 攻击速度
		self.move_speed_frames = 20 # 移动速度

		# 战斗临时数据
		self.id = 0
		self.move_cnt = 0
		self.attack_cnt = 0


	# 向前移动一格
	def move_step(self, x, y):
		self.x = x
		self.y = y
		self.move_cnt = 0


	# 是否活着
	def is_alive(self):
		return self.hp > 0


	# 是否是SIDE_A
	def is_side_a(self):
		return self.side == BATTLE_SIDE_A



class BattleBullet:
	def __init__(self, side, x, y, skill, dmg, hit_n, spd_x, spd_y):
		# 属性
		self.side = side
		self.x = x
		self.y = y
		self.skill = skill
		self.dmg = dmg
		self.hit_n = hit_n
		self.spd_x = spd_x
		self.spd_y = spd_y

		self.src_x = x # 记录起始坐标
		self.src_y = y


	# 移动一步
	def move_step(self):
		pass



class BattleMatrix(object):
	def __init__(self, owner, units):
		self.owner = owner
		self.units = units


	# 是否全死光了
	def is_all_dead(self):
		dead_num = 0
		for u in self.units:
			if not u.is_alive():
				dead_num += 1
		return dead_num >= len(self.units)


	# 取得某个位置的单位
	def get_unit_by_pos(self, x, y):
		for u in self.units:
			if u.x==x and u.y==y:
				return u


	# 取得最近的一个
	def get_nearest_unit(self, unit):
		nearest_len = 0xFFFFFF
		nearest_unit = None

		for u in self.units:
			if not u.is_alive(): continue
			
			l = self._get_length(u, unit)
			if l < nearest_len:
				nearest_len = l
				nearest_unit = u

		return nearest_unit, nearest_len


	def _get_length(self, a, b):
		return math.sqrt( (a.x-b.x) * (a.x-b.x) + (a.y-b.y) * (a.y-b.y) )
		


class MissionBattleMatrix(BattleMatrix):
	def __init__(self, side, wave_data):
		super(MissionBattleMatrix, self).__init__(None, [])
		self.side = side
		# 传入的wave_data格式 {wave_id : [(x, y, enemy_type), ..], ..}
		# 为了使用方便,做一次转换 [[(x, y, enemy_type), ..], ..]
		wave_ids = wave_data.keys()
		wave_ids.sort()
		self.wave_data = [wave_data[wid] for wid in wave_ids]
		print 'self.wave_data:', self.wave_data


	# 把存在wave_data中的数据取出,生成BattleUnits
	def next_wave(self):
		if len(self.wave_data) <= 0: return

		wd = self.wave_data.pop(0)
		untis = []
		for ud in wd:
			x = ud[0]
			y = ud[1]
			type = ud[2]
			skill = DATA_enemy.data[type]['skill']
			is_player = False
			unit = BattleUnit(is_player, self.side, x, y, type, 100,100,100,100, skill)
			# 移动速度
			unit.move_speed_frames = DATA_enemy.data[type]['move_speed'] / (1000 / BATTLE_FRAME_PER_SECOND)
			untis.append(unit)

		self.units = untis	# 放入基类变量中




